package com.example.demo.client;

import com.example.demo.api.SendPrivateMsg;
import com.example.demo.image.RandomImagePicker;
import com.example.demo.kiroBot.Same;
import com.example.demo.kiroBot.Voice;
import jakarta.annotation.PostConstruct;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.websocket.*;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@ClientEndpoint
public class MyWebSocketClient {
    private static final Logger logger = LoggerFactory.getLogger(MyWebSocketClient.class);
    private Session userSession = null;
    private int model = 2;
    private String character = "kiro";
    boolean voice = false;
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    @PostConstruct  // 添加Spring生命周期管理
    public void init() {
        connectToServer();
    }

    private void connectToServer() {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            container.connectToServer(this, new URI("ws://127.0.0.1:3001"));
        } catch (DeploymentException | URISyntaxException | IOException e) {
            logger.error("Failed to connect to server", e);
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        logger.info("Connected to server");
        this.userSession = session;
        startHeartbeat();
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        String msg = ProcessData.message(message);
        JSONObject jsonObject = new JSONObject(msg);
        if (!new JSONObject(message).has("raw_message")){
            return;
        }
        logger.info("Received message: " + jsonObject.getString("msg"));
        if(jsonObject.getString("msg").contains(character)||jsonObject.getString("type").equals("private")){
            if (jsonObject.getString("msg").contains("图片")){
               SendPrivateMsg.SendPostRequest(Data.send(msg,"image",RandomImagePicker.getRandomImagePath("D:\\大葱图")));
               return;
            }else if (jsonObject.getString("msg").contains("模型")){
                SendPrivateMsg.SendPostRequest(Data.sendMessage(msg,"text","请选择模型1，小鲸鱼 2.GPT"));
                return;
            }else if (jsonObject.getString("msg").contains("GPT")){
                model = 1;
                SendPrivateMsg.SendPostRequest(Data.sendMessage(msg,"text","已切换到GPT模型"));
                return;
            }else if (jsonObject.getString("msg").contains("小鲸鱼")){
                model = 2;
                SendPrivateMsg.SendPostRequest(Data.sendMessage(msg,"text","已切换到小鲸鱼模型"));
                return;
            }else if (jsonObject.getString("msg").contains("人设")){
                SendPrivateMsg.SendPostRequest(Data.sendMessage(msg,"text","Elysia or Kiro"));
                return;
            }else if (jsonObject.getString("msg").contains("爱丽希雅")){
                character = "Elysia";
                SendPrivateMsg.SendPostRequest(Data.sendMessage(msg,"text","亲爱的想我了吗？"));
                return;
            }else if (jsonObject.getString("msg").contains("绮罗")){
                character = "kiro";
                SendPrivateMsg.SendPostRequest(Data.sendMessage(msg,"text","叫我干嘛"));
                return;
            }else if (jsonObject.getString("msg").contains("开启声音")){
                voice = true;
                SendPrivateMsg.SendPostRequest(Data.sendMessage(msg,"text","已开启声音"));
                return;
            }else if (jsonObject.getString("msg").contains("关闭声音")){
                voice = false;
                SendPrivateMsg.SendPostRequest(Data.sendMessage(msg,"text","已关闭声音"));
                return;
            }
            try {
                if (voice){
                    String text = Same.getMessage(jsonObject.getString("msg"),model,character);
                    File file = Voice.generateVoiceFile(text);
                    SendPrivateMsg.SendPostRequest(Data.send(msg,"record",file.getAbsolutePath()));
                }else {
                    SendPrivateMsg.SendPostRequest(Data.send(msg,"text",model,character));
                }
            }catch (Exception e){
                System.out.println(e);
            }
        }
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("Session " + session.getId() + " closed because " + closeReason);
        stopHeartbeat();
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("Error on session " + session.getId());
        throwable.printStackTrace();
        stopHeartbeat();
    }

    private void startHeartbeat() {
        scheduler.scheduleAtFixedRate(() -> {
            try {
                if (userSession != null && userSession.isOpen()) {
                    userSession.getBasicRemote().sendText("heartbeat");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, 0, 30, TimeUnit.SECONDS); // 每30秒发送一次心跳
    }
    private void stopHeartbeat() {
        scheduler.shutdown();
    }
}
